<?php

declare(strict_types=1);

namespace app\admin\controller;

use think\Request;
use app\admin\model\MenuModel;
use app\admin\model\RoleModel;

class Home
{
    // 使用检查登录的中间件
    protected $middleware = ['checklogin'];

    /**
     * 后台首页
     */
    public function index(Request $request)
    {
        $admin = $request->_admin;
        $role = RoleModel::where('id', $admin['role_id'])->find();
        if ($role) {
            $role->powers = $role->powers ? json_decode($role->powers, true) : [];
        }

        if ($role->powers) {
            $powers = implode(',', $role->powers);
            $menus = MenuModel::where([
                ['id', 'in', $powers],
                ['ishidden', '=', 0],
                ['status', '=', 1],
            ])->select()->toArray();

            $menus && $menus = $this->getTree($this->cates($menus, 'id'));
        }


        return view('index', ['username' => $admin['username'], 'rolename' => $role->name, 'menus' => $menus]);
    }

    /**
     * 后台欢迎页
     */
    public function welcome()
    {
        return view('welcome');
    }

    /**
     * 退出登录
     */
    public function logout()
    {
        session('admin', null);
        session('rcvr', null);
        return json(['code' => 200]);
    }


    /**
     * 自定义数组索引
     * @param array $lists
     * @param string $index
     * @return array|null
     */
    private function cates(array $lists, string $index): array
    {
        if (!$lists) {
            return $lists;
        }

        $result = [];
        foreach ($lists as $key => $value) {
            $result[$value[$index]] = $value;
        }
        return $result;
    }


    /**
     * 数组转树
     * @param array $items
     * @return array
     */
    private function getTree(array $items): array
    {
        $tree = [];

        foreach ($items as $item) {
            // 判断成员pid是否存在
            if (isset($items[$item['pid']])) {
                // pid不为空时添加children成员，
                $items[$item['pid']]['children'][] = &$items[$item['id']];
            } else {
                // 没有父id直接放入tree
                $tree[] = &$items[$item['id']];
            }
        }
        return $tree;
    }
}